<template>
  <div class="bottom_box">
    <div class="left_btn">
      <!-- 判断当前工单操作按钮总个数 -->
      <div class="bth_box" v-if=" (btn_list.length + total_operation.length) <= 3 ">
        <div @click="clickButton(item)" v-for="(item,index) in btn_list" :key="index" class="forward">
          <p :class="['icon-image', 'iconfont', item.iconClass]"></p>
          <span>{{item.name}}</span>
        </div>
      </div>

      <div class="bth_box" v-else>
        <div @click="clickButton(item)" v-for="(item,index) in btn_list.slice(0,2)" :key="index" class="forward">
          <p :class="['icon-image', 'iconfont', item.iconClass]"></p>
          <span>{{item.name}}</span>
        </div>
        <div class="more" @click="more">
          <p class="icon-image iconfont icon-gengduo"></p>
          <span>更多</span>
        </div>
      </div>
    </div>
    
    <div class="right_btn" v-if="isParticipant">
      <div class="btn_box" @click="clickTransition(transition_refuse)" :class="Object.keys(transition_refuse).length == 0?'transparent':''">
        <div>{{Object.keys(transition_refuse).length == 0?'拒绝':transition_refuse.transition_name}}</div>
      </div>
      <div class="btn_box" @click="clickTransition(transition_agree)" :class="Object.keys(transition_agree).length == 0?'transparent':''">
        <div>{{Object.keys(transition_agree).length == 0?'同意':transition_agree.transition_name}}</div>
      </div>
    </div>

    <van-dialog 
      v-model="is_show_btn" 
      show-cancel-button 
      :closeOnClickOverlay='true'
      :showConfirmButton='false'
      :showCancelButton='false'
      :closeOnPopstate ='true'
      min-heihgt='200px'
    >
      <div>
        <p v-for="(item,index) in btn_list.slice(2)" :key="index" @click="clickButton(item)">{{item.name}}</p>
      </div>
      <div v-if="isParticipant">
        <p v-for="(item,index) in total_operation" :key="index" @click="handleTicket(item)">{{item.transition_name}}</p>
      </div>
      <span @click="is_show_btn = false" class="cancel">取消</span>
    </van-dialog>
  </div>
</template>

<script>
import { Dialog } from 'vant';
export default {
  props:{
    tickteDetails:{
      type:Object,
      required:true,
    },
  },
  data(){
    return{
      total_operation:[],
      is_show_btn:false,
      btn_list:[],
      trigger:'',
      transition_refuse:{},//拒绝按钮数据
      transition_agree:{},//同意按钮数据
      Operation_list:[],
      isParticipant:false,//是否是参与人
      participantList:[],//参与人列表
    }
  },
  watch:{
    
  },
  created(){
    this.getOperation()
    this.judgeIsParticipant()
  },
  methods:{
    //获取后端返回按钮
    getOperation(){
      this.$store.dispatch('api_get_ticket_transitions',this.$route.query.ticket_id).then(res=>{
        this.Operation_list = res.data.data.value
        if(!this.Operation_list){
          this.Operation_list = []
        }
        
        //循环当前所有的操作按钮，将同意和拒绝按钮提取出来，单独展示
        this.total_operation = []
        this.Operation_list.forEach((item,index) => {
          if(item.attribute_type_id == 2){
            this.transition_refuse = item
          }else if(item.attribute_type_id == 1){
            this.transition_agree = item
          }else{
            this.total_operation.push(item)
          }
        })
      })
    },
    //判断当前用户是否是当前工单参与人
    judgeIsParticipant(){
      let _id = this.tickteDetails.participant_type_id
      const getUserList = (params) => {
        this.$store.dispatch("getUserList",params).then(res=>{
          res.data.users.forEach(item=>{
            if(JSON.parse(this.$U.getCache('user')).username == item.username){
              this.isParticipant = true
              this.participantList.push(item.username)
            }
          })
          this.getBtnList()
        })
      }

      let data = {}
      if(_id == 4){//角色
        data.label_ids = this.tickteDetails.participant
        getUserList(data)
      }else if(_id == 3){//部门
        data.org_ids = this.tickteDetails.participant
        getUserList(data)
      }else{
        let list = this.tickteDetails.participant.split(",")
        list.forEach(item=>{
          if(JSON.parse(this.$U.getCache('user')).username == item){
            this.isParticipant = true
            this.participantList.push(item)
          }
        })
        this.getBtnList()
      }
    },
    //前端根据用户权限/工单状态自定义按钮
    getBtnList(){
      this.btn_list = []
      if(JSON.parse(this.$U.getCache('user')).username == this.tickteDetails.creator && this.tickteDetails.act_state_id == 1){
        this.btn_list.push({
          name:'催办',
          iconClass:"icon-cuiban",
          incident:'urgeTicket',
        })
      }
      // 当前用户是工单创建人且工单允许撤销 
      if(JSON.parse(this.$U.getCache('user')).username == this.tickteDetails.creator && this.tickteDetails.state_info.enable_retreat){
        this.btn_list.push({
          name:'撤销',
          iconClass:"icon-chexiao",
          incident:'retreat',
        })
      }
      this.btn_list.push({
        name:'评论',
          iconClass:"icon-pinglun",
          incident:'comment',
      })
      this.btn_list.push({
        name:'打印',
        iconClass:"icon-dayin1",
        incident:'print',
      })
      //当前用户是工单参与人
      if(this.isParticipant){
        this.btn_list.push({
          name:'转交',
          iconClass:"icon-zhuanjiao",
          incident:'deliver',
        },{
          name:'加签',
          iconClass:"icon-jia",
          incident:'add_node',
        })
      }
      
      //当前用户必须是创建人，且工单是初始状态
      if(JSON.parse(this.$U.getCache('user')).username == this.tickteDetails.creator && this.tickteDetails.act_state_id == 0 ){
        this.btn_list.push({
          name:'关闭',
          iconClass:"icon-guanbi",
          incident:'close',
        })
      }
    },
    clickButton(item){
      if(item.incident == 'urgeTicket'){//催办
        this.urgeTicket()
      }else if(item.incident == 'comment'){//评论
        this.comment(item.incident)
      }else if(item.incident == 'deliver' || item.incident == 'add_node'){//转交，加签
        this.choose(item.incident,item.name)
      }else if(item.incident == 'print'){
        this.printTicket()
      }else{
        this.changeTicket(item) //撤销
      }
      this.is_show_btn = false
    },
    //处理工单
    handleTicket(item){
      let incident = 'handleTicket'
      if(item.is_accept){// 接单
        this.changeTicket(item)
      }else if(item.in_add_node){
        incident = 'in_add_node'
      }

      // 点击后台返回的处理工单的按钮时，获取表单数据 
      this.$parent.getForm(item,incident)
    },
    skipToHandleTicket(item,incident,data={}){
      this.$router.push({
        name:'handleTicket',
        query:{
          incident,
          ticket_id:this.tickteDetails.id,
          transition_id:item.transition_id,
          transition_name:item.transition_name,
          creator:this.tickteDetails.creator_info.alias,
          attribute_type_id:item.attribute_type_id,
          workflow_name:this.$route.query.workflow_name,
          data,
        }
      })
    },
    clickTransition(item){
      if(Object.keys(item).length == 0){
        return
      }
      this.handleTicket(item)
    },
    comment(incident){
      this.$router.push({
        name:"comment",
        query:{
          ticket_id:this.tickteDetails.id,
          incident,
          creator:this.tickteDetails.creator_info.alias,
          transition_name:"发送",
          workflow_name:this.$route.query.workflow_name
        }
      })
    },
    choose(incident,name){
      this.trigger = incident
      this.$parent.showContact(name)
      // 选择转交对象后跳转发布转交意见页面
    },
    deliverTicket(list){
      let name = this.trigger == "deliver"?"转交":"加签"
      this.$router.replace({
        name:"deliverTicket",
        query:{
          ticket_id:this.tickteDetails.id,
          incident:this.trigger,
          creator:this.tickteDetails.creator_info.alias,
          transition_name:name,
          user_list:JSON.stringify(list),
          workflow_name:this.$route.query.workflow_name
        }
      })
    },
    urgeTicket(){
      // 调用钉钉发DING接口 
      this.$dd.ready(()=>{
        this.$dd.biz.ding.create({
          users : this.participantList,// 用户列表，工号
          corpId: this.$store.getters.corpId, // 企业id
          type: 2, // 附件类型 1：image  2：link
          alertType: 2, // 钉发送方式 0:电话, 1:短信, 2:应用内
          alertDate: {"format":"yyyy-MM-dd HH:mm","value":"2015-05-09 08:00"},
          attachment: {
            title: '待办任务通知', //附件的标题
            url: `http://howflow.leadot.com.cn/#/TicketDetails?ticket_id=${this.tickteDetails.id}&workflow_name=${this.$route.query.workflow_name}`, //附件点击后跳转url
            image: 'https://howflow-1253590499.cos.ap-chengdu.myqcloud.com/static/urge.png', //附件显示时的图片 【可选】
            text: this.tickteDetails.creator_info.alias + "提交的工单需要您查看审批，请点击查看", //附件显示时的消息体 【可选】
            showInApp: true, // 跳转url在PC客户端上的打开方式，true：从PC容器内打开，false：跳转到浏览器打开 【可选】
          },
          text: this.tickteDetails.creator_info.alias + "提醒您审批他的工单",  // 正文
          bizType :0, // 业务类型 0：通知DING；1：任务；2：会议；
          confInfo:{
            bizSubType:0, // 子业务类型如会议：0：预约会议；1：预约电话会议；2：预约视频会议；（注：目前只有会议才有子业务类型）
            location:'某某会议室' , //会议地点；（非必填）
            startTime:{"format":"yyyy-MM-dd HH:mm","value":"2015-05-09 08:00"},// 会议开始时间
            endTime:{"format":"yyyy-MM-dd HH:mm","value":"2015-05-09 08:00"}, // 会议结束时间
            remindMinutes:30, // 会前提醒。单位分钟-1：不提醒；0：事件发生时提醒；5：提前5分钟；15：提前15分钟；30：提前30分钟；60：提前1个小时；1440：提前一天；
            remindType:2 // 会议提前提醒方式。0:电话, 1:短信, 2:应用内
          },
      
          taskInfo:{
            ccUsers: [], // 抄送用户列表，工号
            deadlineTime:{"format":"yyyy-MM-dd HH:mm","value":"2015-05-09 08:00"} , // 任务截止时间
            taskRemind:30// 任务提醒时间，单位分钟0：不提醒；15：提前15分钟；60：提前1个小时；180：提前3个小时；1440：提前一天；
          },
      
          onSuccess : function() {
              //onSuccess将在点击发送之后调用
          },
          onFail : function() {}
       })
      })
    },
    changeTicket(item){
      let _api = 'api_post_' + item.incident
      Dialog.confirm({
        title: '提示',
        message: '您确定要' + item.name + '工单吗?'
      }).then(() => {
        this.$store.dispatch(_api,this.tickteDetails.id).then(res=>{
          if(res.status == 200 ){
             this.$toast.success(item.name + '工单成功');
             this.getOperation()
             this.$parent.refresh()
          }
        }).catch(err=>{
          console.log(err)
          this.$toast.fail(item.name + '工单失败，请稍后重试');
        })
      }).catch(() => {
        
      });
    },
    more(){
      this.is_show_btn = true
    },
    printTicket(){
      let data = {
          field_list:JSON.stringify(this.tickteDetails.field_list),
          id:this.tickteDetails.id,
          gmt_created:this.tickteDetails.gmt_created,
      }
      if(this.$route.query.workflow_name){
        data.workflow_name = this.$route.query.workflow_name
      }else{
        data.workflow_id = this.$route.query.workflow_id
      }
      this.$router.push({
        name:'printTicket',
        query:data
      })
    }
  }
}
</script>

<style lang="less" scoped>
*{
  box-sizing: border-box;
}
.bottom_box{
  box-sizing: border-box;
  position: absolute;
  bottom: 0px;
  width: 100%;
  height: 50px;
  border-top:1px solid #E5E5E5;
  padding: 7px 10px 7px 10px;
  display: flex;
  background: #fff;
  .left_btn{
    display: flex;
    flex:1;
    .bth_box{
      display: flex;
      flex:1;
      >div{
        display: flex;
        flex:1;
        height: auto;
        text-align: center;
        font-size: 10px;
        flex-direction: column;
        justify-content: space-around;
        p{
          margin:2px 0;
          font-size: 16px;
        }
      }
    }
  }
  .right_btn{
    width: auto;
    height: auto;
    display: flex;
    flex:1;
    overflow: hidden;
    .btn_box{
      padding: 1px;
      border:1px solid #DADADA;
      border-right: none;
      border-radius: 5px 0px 0px 5px;
      flex:1;
      display: flex;
      align-items:center;
      justify-content: center;
      font-size: 14px;
      color:#38A0F2;
    }
    .transparent{
      opacity: 0.5;
    }
    >:nth-child(2){
      border:1px solid #3295FA;
      border-left:none;
      border-radius: 0px 5px 5px 0px;
      background: #3295FA;
      color: #fff;
    }
  }
  .van-dialog{
    width: 7.4667rem;
    min-height: 4.8rem;
    padding:0.5333rem;
    padding-bottom:0.9333rem;
    p{
      margin:0;
      font-size:14px; 
      line-height: 0.9333rem;
    }
    .cancel{
      font-size: 12px;
      position: absolute;
      right: 0.6667rem;
      bottom:0.2667rem;
      color:#38A0F2;
    }
  }
}
</style>